const { Wechaty } = require('wechaty');
const { getMonitorRecord } = require('./utils/index')
const { monitorRoomList } = require('./config/index')

const bot = new Wechaty({
  name: 'dota2-bot', // 机器人名字
  puppet: 'wechaty-puppet-wechat' // 协议类型
});

let timer; // 定时器

// 延时函数
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

//  二维码生成
function onScan(qrcode, status) {
  require('qrcode-terminal').generate(qrcode); // 在console端显示二维码
  const qrcodeImageUrl = [
    'https://wechaty.js.org/qrcode/',
    encodeURIComponent(qrcode),
  ].join('');
  console.log(qrcodeImageUrl);
}

// 登录
async function onLogin(user) {
  console.log(`${user}登录了`);
  recordMonitor()
}

// 登出
function onLogout(user) {
  if(timer) clearTimeout(timer)
  console.log(`${user} 已经登出`);
}

// 加群
async function onRoomInvitation(roomInvitation) {
  try {
    console.log(roomInvitation)
    const inviter = await roomInvitation.inviter()
    const name = inviter.name()
    console.log(`邀请人 ${name}`)
    await roomInvitation.accept()
  } catch (e) {
    console.error(e)
  }
}

// 进群
async function onRoomJoin(room, inviteeList, inviter) {
  const nameList = inviteeList.map(c => c.name()).join(',')
  await room.say(`欢迎新群友${nameList}!`)
  console.log(`Room ${await room.topic()} got new member ${nameList}, invited by ${inviter}`)
}

// 退群
async function onRoomLeave(room, leaverList, remover) {
  const nameList = leaverList.map(c => c.name()).join(',')
  await room.say(`${nameList}离开了群聊，祝ta生活愉快吧`)
  console.log(`Room ${await room.topic()} lost member ${nameList}, the remover is: ${remover}`)
}

// 改群名
async function onRoomTopic(room, topic, oldTopic, changer) {
  console.log(`Room ${await room.topic()} topic changed from ${oldTopic} to ${topic} by ${changer.name()}`)
}

// 加好友
async function onFriendship(friendship) {
  console.log(`received friend event from ${friendship.contact().name()}`)
}

// 监听对话
async function onMessage(msg) {
  const contact = msg.talker(); // 发消息人
  const content = msg.text().trim(); // 消息内容
  const room = msg.room(); // 是否是群消息
  const alias = await contact.alias() || await contact.name(); // 发消息人备注
  const isText = msg.type() === bot.Message.Type.Text; // 是否文字消息
  const isEmoticon = msg.type() === bot.Message.Type.Emoticon // 是否表情消息
  if (msg.self()) { // 是否自己发送的消息
    return;
  }

  if (room && isText) {
    // 如果是群消息 目前只处理文字消息
    const topic = await room.topic();
    console.log(`群名: ${topic} 发消息人: ${await contact.name()} id: ${await contact.id} 内容: ${content}`);

  } else if (isText) {
    // 如果非群消息 目前只处理文字消息
    console.log(`发消息人: ${alias} 消息内容: ${content}`);
  }
}

// 监控Dota游戏
function recordMonitor() {
  recordMonitorStart()
  timer = setTimeout(() => {
    recordMonitor()
  }, 600000)
}

async function recordMonitorStart() {
  for (let i = 0; i < monitorRoomList.length; i++) {
    for (let j = 0; j < monitorRoomList[i].monitorMemberList.length; j++) {
      const res = await getMonitorRecord(monitorRoomList[i].monitorMemberList[j])
      await delay(1000)
      if (res.msg) {
        const room = await bot.Room.find({ topic: monitorRoomList[i].topic })
        await room.say(res.msg)
      }
    }
  }
}

bot.on('scan', onScan)
bot.on('login', onLogin)
bot.on('logout', onLogout)
bot.on('message', onMessage)
bot.on('room-invite', onRoomInvitation)
bot.on('room-join', onRoomJoin)
bot.on('room-leave', onRoomLeave)
bot.on('room-topic', onRoomTopic)
bot.on('friendship', onFriendship)
bot
  .start()
